package common.web.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import util.StringUtil;
import util.idgenerator.IDGeneratorUtil;

import common.serialization.IWebText;
import common.serialization.XmlDataBean;
import common.service.BaseService;
import common.service.CacheService;
import common.service.IService;
import common.service.ServiceFactory;
import common.web.WebHelper;

public class TreeAction {
	//获取树型数据,构造成xml,未排序
	public static IWebText getTreeData(HttpServletRequest request) throws Exception {
		String tableName = request.getParameter("tableName");
		
		XmlDataBean root = new XmlDataBean();
		root.setNameSpace("tree");
		root.setId("0");
		
		IService service = new BaseService();
		List<Map<String,Object>> list = service.queryBySql("select * from " + StringUtil.getTableName(tableName) + " order by PATH " );
		for(Map<String,Object> map : list) {
			String id = (String)map.get("ID");
			String pid = (String)map.get("PID");
			
			XmlDataBean child = new XmlDataBean();
			child.setNameSpace("item");
			child.setId(id);
			child.setAttribute("text", (String)map.get("NAME"));
			
			//加到父节点
			root.findXmlDataBean(pid).appendChildXmlDataBean(child);
		}
		return root;
	}
	
	//根据父ID获取树型数据
	public static IWebText getTreeDataByPid(HttpServletRequest request)throws Exception {
		String tableName = request.getParameter("tableName");
		String pid = request.getParameter("pid");

		XmlDataBean root = new XmlDataBean();
		root.setNameSpace("tree");
		root.setId(pid);

		IService service = new BaseService();
		String sql = "select * from "+ StringUtil.getTableName(tableName) + " where ID<>'" + pid + "' and PATH like '%" + pid + ",%' order by PATH ";
		List<Map<String, Object>> list = service.queryBySql(sql);
		for (Map<String, Object> map : list) {
			String id = (String)map.get("ID");
			String PID = (String)map.get("PID");
			
			XmlDataBean child = new XmlDataBean();
			child.setNameSpace("item");
			child.setId(id);
			child.setAttribute("text", (String)map.get("NAME"));
			
			//加到父节点
			root.findXmlDataBean(PID).appendChildXmlDataBean(child);
		}
		return root;
	}
	
	//保存树型数据
	public static void doSave(HttpServletRequest request) throws Exception {
		//获取service的代理类
		WebHelper webHelper = new WebHelper();
		webHelper.setRequest(request);
		IService service = ServiceFactory.getService(null,webHelper);
		
		service.saveTreeData();
		
	}
	
}
